/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 *
 * @author PHINGUYEN
 */
public class TestLoad {

    public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        String path = "C:/";

        PublicKey pubKey;
        PrivateKey priKey;

//        byte[] encryptedOutput = LoadEncripted(path);
        
        
        KeyPair key = LoadKeyPair(path, "RSA");
        pubKey = key.getPublic();
        priKey = key.getPrivate();

//        Cipher cipher = Cipher.getInstance("RSA");
//        cipher.init(Cipher.DECRYPT_MODE, priKey);
//        decryptedOutput = cipher.doFinal(encryptedOutput);
        
//        byte[] decryptedOutput = DecryptRSA(encryptedOutput, priKey);
//        System.out.println("Text:" + new String(decryptedOutput));
        try {
            Class.forName(("com.microsoft.sqlserver.jdbc.SQLServerDriver"));
            System.out.println("load driver successfully...");
            Connection conn = DriverManager.getConnection("jdbc:sqlserver://ANHPHI;databaseName=TestEncrypt;user=sa;password=1234567");
            System.out.println("got connection.....");
            Statement state = conn.createStatement();
            String sql = "SELECT * FROM Content";
            ResultSet result = state.executeQuery(sql);
            System.out.println("result set successfull...");
//            byte[] decryptedOutput = null;
            while (result.next()) {
                byte[] decryptedOutputTmp = result.getBytes("content");
//                int in = decryptedOutputTmp.length;
                byte[] decryptedOutput = DecryptRSA(decryptedOutputTmp, priKey);
                System.out.println(new String(decryptedOutput));
            }
            

//            System.out.println("Text: " + new String(decryptedOutput));
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(TestLoad.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }


    }

    public static KeyPair LoadKeyPair(String path, String algorithm) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        File filePubKey = new File(path + "pub.key");
        byte[] encodedPubKey = new byte[(int) filePubKey.length()];
        FileInputStream fis = new FileInputStream(path + "pub.key");
        fis.read(encodedPubKey);
        fis.close();

        File filePriKey = new File(path + "pri.key");
        byte[] encodedPriKey = new byte[(int) filePriKey.length()];
        fis = new FileInputStream(path + "pri.key");
        fis.read(encodedPriKey);
        fis.close();

        KeyFactory keyFac = KeyFactory.getInstance(algorithm);
        X509EncodedKeySpec x509 = new X509EncodedKeySpec(encodedPubKey);
        PublicKey pubKey = keyFac.generatePublic(x509);
        PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(encodedPriKey);
        PrivateKey priKey = keyFac.generatePrivate(pkcs8);

        KeyPair key = new KeyPair(pubKey, priKey);
        return key;
    }

    public static byte[] LoadEncripted(String path) throws FileNotFoundException, IOException, IOException {

//        BufferedReader buf = new BufferedReader(new FileReader(path + "encrypt.txt"));
//        String line;
//        while((line = buf.readLine())!=null){
//            line = buf.readLine();
//        }
//        
//        return line;
        File fileEncrypted = new File(path + "encrypt.txt");
        byte[] encrypte = new byte[(int)fileEncrypted.length()];
        FileInputStream fis = new FileInputStream(path  + "encrypt.txt");
        fis.read(encrypte);
        fis.close();

        return encrypte;
    }
    
    public static byte[] DecryptRSA(byte[] byte1,PrivateKey priKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, IllegalBlockSizeException, IllegalBlockSizeException, BadPaddingException{
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        byte[] decryptedOutput = cipher.doFinal(byte1) ;
        return decryptedOutput;
    }
}
